local homes_file = minetest.get_worldpath() .. "/beds_spawns"
local homepos = {}

local function loadhomes()
    local input = io.open(homes_file, "r")
    if input then
      repeat
            local x = input:read("*n")
            if x == nil then
               break
            end
            local y = input:read("*n")
            local z = input:read("*n")
            local name = input:read("*l")
            homepos[name:sub(2)] = {x = x, y = y, z = z}
        until input:read(0) == nil
        io.close(input)
    else
        homepos = {}
    end
end

minetest.register_privilege("home", "Can use /sethome and /home")

minetest.register_chatcommand("home", {
    description = "Teleport you to your home point",
    privs = {home=true},
    func = function(name)
        local player = minetest.get_player_by_name(name)
        if player == nil then
            -- just a check to prevent the server crashing
            return false
        end
      loadhomes()
        if homepos[name] then
            player:setpos(homepos[name])
            player:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0})    
            player:set_physics_override(1, 1, 1)
            --minetest.chat_send_player(name, "Teleported to home!")
        else
            minetest.chat_send_player(name, "You haven't slept in a bed yet.")
        end
    end,
})

minetest.register_chatcommand("sethome", {
    description = "Information about set your home point",
    func = function(name)
      minetest.chat_send_player(name, "You must sleep in a bed for this.")
    end,
})
